#pragma once
#include <string>
#include <cstring>

namespace wyl
{
#define SEP "\r\n"
    class Util
    {
    public:
        static std::string GetLine(std::string &message)
        {
            //  GET / HTTP/1.0
            size_t pos = message.find(SEP);
            if (pos == std::string::npos)
                return "";
            std::string sub = message.substr(0, pos);
            message.erase(0, sub.size() + strlen(SEP));
            return sub;
        }

        static bool CutString(const std::string &str, std::string *key, std::string *value, const std::string &sep)
        {
            size_t pos = str.find(sep);
            if (pos == std::string::npos)
                return false;
            // 0 - pos , pos + 1 -...
            *key = str.substr(0, pos);
            *value = str.substr(pos + 1);
            return true;
        }

        //解码
       static std::string Decode(const std::string &str)
        {
            std::string ret;
            int begin = 0;
            while (1)
            {
                // C%2B%2B
                size_t pos = str.find("%", begin);
                if (pos == std::string::npos)
                    break;
                ret += str.substr(begin, pos - begin);
                char op1 = str[pos + 1];
                char op2 = str[pos + 2];
                char ch = 0;
                // 解码op1
                if (op1 >= '0' && op1 <= '9')
                {
                    ch += (op1 - '0') * 16;
                }
                else if (op1 >= 'A' && op1 <= 'Z')
                {
                    ch += (op1 - 'A' + 10) * 16;
                }
                else if (op1 >= 'a' && op1 <= 'z')
                {
                    ch += (op1 - 'a' + 10) * 16;
                }

                // 解码op2
                if (op2 >= '0' && op2 <= '9')
                {
                    ch += op2 - '0';
                }
                else if (op2 >= 'A' && op2 <= 'Z')
                {
                    ch += op2 - 'A' + 10;
                }
                else if (op2 >= 'a' && op2 <= 'z')
                {
                    ch += op2 - 'a' + 10;
                }
                ret += ch;
                pos += 3;
                begin = pos;
            }
            ret += str.substr(begin);
            return ret;
        }
    };

}